#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
云账户相关数据模型
"""

from sqlalchemy import Column, Integer, String, Boolean, DateTime, Index, Text
from sqlalchemy.orm import Session
from datetime import datetime
from typing import List, Optional
from .base import Base, BaseRepository, QueryCondition


class CloudAccount(Base):
    """云盘账户表"""
    __tablename__ = 'cloud_accounts'
    
    id = Column(Integer, primary_key=True, autoincrement=True, comment='主键ID')
    cloud_provider = Column(String(50), nullable=False, comment='云盘提供商')
    cloud_account = Column(String(100), nullable=False, comment='云盘账号')
    cloud_password = Column(String(255), nullable=False, comment='云盘密码')
    display_name = Column(String(100), comment='显示名称')
    is_active = Column(Boolean, default=True, comment='是否激活')
    # Token相关字段
    access_token = Column(Text, comment='访问令牌')
    refresh_token = Column(Text, comment='刷新令牌')
    session_key = Column(String(255), comment='会话密钥')
    session_secret = Column(String(255), comment='会话密钥')
    token_expires_at = Column(DateTime, comment='令牌过期时间')
    last_login_at = Column(DateTime, comment='最后登录时间')
    created_at = Column(DateTime, default=datetime.utcnow, comment='创建时间')
    updated_at = Column(DateTime, default=datetime.utcnow, onupdate=datetime.utcnow, comment='更新时间')
    
    # 索引
    __table_args__ = (
        Index('idx_cloud_account', 'cloud_provider', 'cloud_account'),
    )


class CloudResource(Base):
    """云盘资源表"""
    __tablename__ = 'cloud_resources'
    
    id = Column(Integer, primary_key=True, autoincrement=True, comment='主键ID')
    clouds_type = Column(String(50), nullable=False, comment='云盘类型')
    share_code = Column(String(100), nullable=False, comment='分享码')
    access_code = Column(String(100), comment='访问码')
    share_name = Column(String(500), comment='分享名称')
    full_url = Column(String(1000), comment='完整URL')
    share_status = Column(String(50), default='active', comment='分享状态')
    share_time = Column(DateTime, comment='分享时间')
    file_info_json = Column(Text, comment='文件信息JSON')
    created_at = Column(DateTime, default=datetime.utcnow, comment='创建时间')
    updated_at = Column(DateTime, default=datetime.utcnow, onupdate=datetime.utcnow, comment='更新时间')
    
    # 索引
    __table_args__ = (
        Index('idx_clouds_type', 'clouds_type'),
        Index('idx_share_code', 'share_code'),
        Index('idx_created_at', 'created_at'),
    )


class CloudAccountRepository(BaseRepository):
    """云账户Repository"""
    
    def __init__(self, session: Session):
        super().__init__(session, CloudAccount)
    
    def find_by_provider(self, cloud_provider: str) -> List[CloudAccount]:
        """根据云服务提供商查找账户"""
        condition = QueryCondition()
        condition.eq(CloudAccount.cloud_provider, cloud_provider)
        return self.list_by_condition(condition, order_by='display_name')
    
    def find_by_account(self, cloud_provider: str, cloud_account: str) -> Optional[CloudAccount]:
        """根据提供商和账号查找"""
        condition = QueryCondition()
        condition.eq(CloudAccount.cloud_provider, cloud_provider)
        condition.eq(CloudAccount.cloud_account, cloud_account)
        return self.get_one(condition)
    
    def find_active_accounts(self) -> List[CloudAccount]:
        """查找所有活跃账户"""
        condition = QueryCondition()
        condition.eq(CloudAccount.is_active, True)
        return self.list_by_condition(condition, order_by='cloud_provider')
    
    def find_by_display_name(self, display_name: str) -> Optional[CloudAccount]:
        """根据显示名称查找账户"""
        condition = QueryCondition()
        condition.eq(CloudAccount.display_name, display_name)
        return self.get_one(condition)
    
    def create_account(self, cloud_provider: str, cloud_account: str, cloud_password: str, 
                      display_name: str = None) -> CloudAccount:
        """创建云账户"""
        account = CloudAccount(
            cloud_provider=cloud_provider,
            cloud_account=cloud_account,
            cloud_password=cloud_password,
            display_name=display_name or cloud_account
        )
        return self.save(account)
    
    def update_password(self, account_id: int, new_password: str) -> bool:
        """更新密码"""
        return self.update_by_id(account_id, cloud_password=new_password)
    
    def activate_account(self, account_id: int) -> bool:
        """激活账户"""
        return self.update_by_id(account_id, is_active=True)
    
    def deactivate_account(self, account_id: int) -> bool:
        """停用账户"""
        return self.update_by_id(account_id, is_active=False)
    
    def update_display_name(self, account_id: int, display_name: str) -> bool:
        """更新显示名称"""
        return self.update_by_id(account_id, display_name=display_name)


class CloudResourceRepository(BaseRepository):
    """云盘资源Repository"""
    
    def __init__(self, session: Session):
        super().__init__(session, CloudResource)
    
    def find_by_clouds_type(self, clouds_type: str) -> List[CloudResource]:
        """根据云盘类型查找资源"""
        condition = QueryCondition()
        condition.eq(CloudResource.clouds_type, clouds_type)
        return self.list_by_condition(condition, order_by='created_at', desc_order=True)
    
    def find_by_share_code(self, share_code: str) -> Optional[CloudResource]:
        """根据分享码查找资源"""
        condition = QueryCondition()
        condition.eq(CloudResource.share_code, share_code)
        return self.get_one(condition)
    
    def find_by_status(self, share_status: str) -> List[CloudResource]:
        """根据分享状态查找资源"""
        condition = QueryCondition()
        condition.eq(CloudResource.share_status, share_status)
        return self.list_by_condition(condition, order_by='created_at', desc_order=True)
    
    def create_resource(self, clouds_type: str, share_code: str, access_code: str = None,
                       share_name: str = None, full_url: str = None, 
                       file_info_json: str = None) -> CloudResource:
        """创建云盘资源"""
        resource = CloudResource(
            clouds_type=clouds_type,
            share_code=share_code,
            access_code=access_code,
            share_name=share_name,
            full_url=full_url,
            file_info_json=file_info_json
        )
        return self.save(resource)
    
    def update_status(self, resource_id: int, share_status: str) -> bool:
        """更新分享状态"""
        return self.update_by_id(resource_id, share_status=share_status)
    
    def update_file_info(self, resource_id: int, file_info_json: str) -> bool:
        """更新文件信息"""
        return self.update_by_id(resource_id, file_info_json=file_info_json)